/*
   Copyright 2011-2012 gtalent2@gmail.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package combat

import (
	critter "../entity"
	"github.com/gtalent/starfish/gfx"
	"github.com/gtalent/starfish/util"
	"strconv"
)

type level struct {
	gfx.Text
	level int
}

type name struct {
	gfx.Text
	name string
}

type combatantSpec struct {
	Creature *creature
	font     *gfx.Font
	name     name
	level    level
	width    int
	height   int
}

func newCombatantSpec(font *gfx.Font) *combatantSpec {
	cs := new(combatantSpec)
	cs.width = 150
	cs.font = font
	return cs
}

//Returns an indicator of success
func (me *combatantSpec) update(c *critter.Creature) bool {
	if !me.font.WriteTo("Level: "+strconv.Itoa(me.Creature.Level), &me.level.Text) {
		return false
	}
	if !me.font.WriteTo(me.Creature.Name, &me.name.Text) {
		return false
	}
	return true
}

func (me *combatantSpec) Draw(c *gfx.Canvas, loc util.Point) {
	if me.Creature.Level != me.level.level {
		me.font.WriteTo("Level: "+strconv.Itoa(me.Creature.Level), &me.level.Text)
	}
	if me.Creature.Name != me.name.name {
		me.font.WriteTo(me.Creature.Name, &me.name.Text)
	}

	startY := loc.Y - 2

	// full width
	full := me.width

	c.SetRGBA(0, 0, 0, 255)
	c.FillRoundedRect(loc.X-2, loc.Y-2, full+4, 20+4+me.level.Height()+me.name.Height(), 1)

	c.SetRGBA(255, 255, 255, 255)
	c.FillRoundedRect(loc.X, loc.Y, full, 20+me.level.Height()+me.name.Height(), 1)
	c.DrawText(&me.name.Text, loc.X, loc.Y)
	loc.Y += me.name.Height()
	c.DrawText(&me.level.Text, loc.X, loc.Y)

	loc.Y += me.level.Height()

	c.SetRGBA(0, 0, 0, 255)
	c.FillRoundedRect(loc.X-2, loc.Y-2, full+4, 20+4, 1)
	c.FillRect(loc.X-2, loc.Y-2, full+4, 1)

	c.SetRGBA(255, 255, 255, 255)
	c.FillRoundedRect(loc.X, loc.Y, full, 20, 1)
	hp := &me.Creature.Health
	if hp.Current != 0 {
		width := (hp.Current * full) / hp.Available
		switch {
		case width > (full / 2):
			//green
			c.SetRGB(34, 139, 34)
		case width > (full / 4):
			//yellow
			c.SetRGB(255, 215, 0)
		default:
			//red
			c.SetRGB(178, 34, 34)
		}
		c.FillRoundedRect(loc.X, loc.Y, width, 20, 1)
		if width < 150 {
			c.FillRect(loc.X+1, loc.Y, width-1, 20)
		}
	}
	me.height = loc.Y - startY
}
